package kotan.view.table.editor;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JComponent;
import javax.swing.JDialog;

import kotan.Kotan;
import kotan.datastore.api.Key;
import kotan.model.KindModel;

/**
 * Dialog to edit key
 * @author shuji.w6e
 * @since 1.0
 * @see Key
 */
public class KeyEditorDialog {

    /**
     * 
     * @param parentComponent
     * @param model
     * @param key
     */
    public static void showDialog(JComponent parentComponent, KindModel model, Key key) {
        JDialog dialog = new JDialog(Kotan.get().getMainFrame());
        dialog.setTitle("Key editor");
        final KeyEditorPanel panel = createPanel(dialog);
        dialog.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                panel.applyButton.requestFocusInWindow();
            }
        });
//      dialog.setLocationRelativeTo(parentComponent);
        panel.init(model, key);
        dialog.setVisible(true);
    }

    public static void showCreateDialog(JComponent parentComponent, KindModel model) {
        JDialog dialog = new JDialog(Kotan.get().getMainFrame());
        dialog.setTitle("Key editor");
        final KeyEditorPanel panel = createPanel(dialog);
        dialog.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                panel.idField.requestFocusInWindow();
            }
        });
//      dialog.setLocationRelativeTo(parentComponent);
        panel.init(model, model.allocateKey());
        dialog.setVisible(true);
    }
    
    private static KeyEditorPanel createPanel(final JDialog dialog) {
        @SuppressWarnings("serial")
        final KeyEditorPanel panel = new KeyEditorPanel() {

            @Override
            protected void onApply() {
                super.onApply();
                dialog.dispose();
            }

            @Override
            protected void onCancel() {
                super.onCancel();
                dialog.dispose();
            }

        };
        dialog.add(panel);
        dialog.pack();
        return panel;
    }

}
